package com.example.yang.yixin.Socket;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class Signset {
    /*
    将班课签到状态变为0
     */

    public static void SetSign(String bkpassword, final String control, final Context context, String x, String  y,int time,int endtime, final View view){
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/SigninServlet?bkpassword="+bkpassword
                +"&control="+control+"&locationX="+x+"&locationY="+y+"&starttime="+time+"&endtime="+endtime;
        RequestQueue mQueue = Volley.newRequestQueue(context);


        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Message msg=new Message();
                    boolean flag=response.getBoolean("flag");
                    Handler handler = new Handler()
                    {
                        public  void handleMessage(Message msg)
                        {
                            switch(msg.what)
                            {
                                case 0:


                                    Snackbar.make(view,"签到已开启，请不要忘记结束签到哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();

                                    break;

                                case 1:
                                    Snackbar.make(view,"服务器开小差了稍后再试！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 2:
                                    Snackbar.make(view,"班课暂未开启签到哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 3:
                                    Snackbar.make(view,"签到成功，快刷新查看吧！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 4:
                                    Snackbar.make(view,"签到已结束哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 5:
                                    Snackbar.make(view,"服务器开小差了稍后再试！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;



                            }

                        }
                    };

                    if(control.equals("open")) {
                        if (flag) {

                            msg.what = 0;
                            handler.handleMessage(msg);

                        } else {
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    }else {
                        boolean sign=response.getBoolean("sign");
                        if(flag&&sign){
                            msg.what = 4;
                            handler.sendMessage(msg);
                        }
                        else if(!flag&&!sign){
                            msg.what=5;
                            handler.sendMessage(msg);
                        }
                        else {
                            msg.what=1;
                            handler.sendMessage(msg);
                        }
                    }





                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);

    }
    /*
   将自己的签到状态变为0
    */
    public static boolean GetSign(final String bkpassword, final String username, final Context context, final String mylocationX, final String mylocationY, final int time, final View view){
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ConditionServlet?bkpassword="+bkpassword;
        RequestQueue mQueue = Volley.newRequestQueue(context);


        final boolean[] Success_Or_Defeat = {false};
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Message msg=new Message();
                    Handler handler = new Handler()
                    {
                        public  void handleMessage(Message msg)
                        {
                            switch(msg.what)
                            {
                                case 2:
                                    Snackbar.make(view,"班课暂未开启签到哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 3:
                                    Snackbar.make(view,"签到成功，快刷新查看吧！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 4:
                                    Snackbar.make(view,"签到已结束哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 5:
                                    Snackbar.make(view,"您不在签到范围哦（R=100m）！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;



                            }

                        }
                    };


                   String sign=response.getString("sign");
                   String locationX=response.getString("locationX");
                   String locationY=response.getString("locationY");
                   double location_teracherX=Double.parseDouble(locationX);
                   double location_teracherY=Double.parseDouble(locationY);
                    double location_myY=Double.parseDouble(mylocationY);
                    double location_myX=Double.parseDouble(mylocationX);
                    int  starttime=response.getInt("starttime");
                   if(sign.equals("0")){
                       msg.what=2;
                       handler.sendMessage(msg);
                   }else{
/*
增加距离判
 */                    double distance=GetDistance(location_myY,location_myX,location_teracherY,location_teracherX);
                       if(distance<200.00) {
                           int res=time-starttime;
                           if (res>3) {
                               ChangeSign(bkpassword, username, context, view,"1");
                           }
                           else{
                               ChangeSign(bkpassword, username, context, view,"0");
                           }
                           Success_Or_Defeat[0] =true;
                       }else{
                           msg.what=5;
                           handler.sendMessage(msg);
                       }

                   }
                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }


        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);
        return   Success_Or_Defeat[0];

    }

     static void ChangeSign(String bkpassword, String username, final Context context, final View view,String later) {
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ChangeServlet?bkpassword="+bkpassword+"&username="+username+"&later="+later;
        RequestQueue mQueue = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Message msg=new Message();
                    Handler handler = new Handler()
                    {
                        public  void handleMessage(Message msg)
                        {
                            switch(msg.what)
                            {
                                case 1:
                                    Snackbar.make(view,"服务器开小差了稍后再试！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 2:
                                    Snackbar.make(view,"服务器开小差了稍后再试！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 3:
                                    Snackbar.make(view,"签到成功，快刷新查看吧！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 4:
                                    Snackbar.make(view,"未在规定时间内签到，已记录迟到",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;



                            }

                        }
                    };
                    boolean flag=response.getBoolean("flag");
                    boolean time=response.getBoolean("time");
                    boolean later=response.getBoolean("later");
                    Log.d("flag", "onResponse: "+flag);
                    Log.d("time", "onResponse: "+time);
                    Log.d("later", "onResponse: "+later);
                    if(flag&&time){
                        if(later){
                        msg.what=4;
                        handler.sendMessage(msg);
                        }
                        else{
                            msg.what=3;
                            handler.sendMessage(msg);
                        }
                    }
                    else if(!flag&&!time){
                        msg.what=1;
                        handler.sendMessage(msg);

                    }else{
                        msg.what=2;
                    }






                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }


        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);

    }
    public static void ChangeEarly(String bkpassword, String username, final Context context, final View view) {
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/EndServlet?bkpassword="+bkpassword+"&username="+username;
        RequestQueue mQueue = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Message msg=new Message();
                    Handler handler = new Handler()
                    {
                        public  void handleMessage(Message msg)
                        {
                            switch(msg.what)
                            {
                                case 1:
                                    Snackbar.make(view,"服务器开小差了稍后再试！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 3:
                                    Snackbar.make(view,"签到成功，继续保持哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;



                            }

                        }
                    };
                   boolean flag=response.getBoolean("flag");
                  if(flag){
                     msg.what=3;
                     handler.sendMessage(msg);
                  }else{
                      msg.what=1;
                      handler.sendMessage(msg);
                  }



                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }


        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);

    }
    /*
  将班课签到状态变为1
   */
    public static void GetEndfSign(final String bkpassword, final String username, final Context context, final String mylocationX, final String mylocationY, final int endtime, final View view){
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ConditionServlet?bkpassword="+bkpassword;
        RequestQueue mQueue = Volley.newRequestQueue(context);



        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Message msg=new Message();
                    Handler handler = new Handler()
                    {
                        public  void handleMessage(Message msg)
                        {
                            switch(msg.what)
                            {
                                case 1:
                                    Snackbar.make(view,"未在规定时间内完成签到！(下课后五分钟内!)",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                                case 5:
                                    Snackbar.make(view,"你不在可签到范围！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                    break;
                            }

                        }
                    };


                    String sign=response.getString("sign");
                    String locationX=response.getString("locationX");
                    String locationY=response.getString("locationY");
                    int  end=response.getInt("endtime");
                    double location_teracherX=Double.parseDouble(locationX);
                    double location_teracherY=Double.parseDouble(locationY);
                    double location_myY=Double.parseDouble(mylocationY);
                    double location_myX=Double.parseDouble(mylocationX);
                    Toast.makeText(context,end+"",Toast.LENGTH_LONG).show();

                    if(sign.equals("0")){
                        msg.what=2;
                        handler.sendMessage(msg);
                    }else{
                        double distance=GetDistance(location_myY,location_myX,location_teracherY,location_teracherX);
                        Toast.makeText(context,distance+"",Toast.LENGTH_LONG).show();
                        if(distance<200.00) {
                            int res=endtime-end;
                            Toast.makeText(context,res+"",Toast.LENGTH_LONG).show();
                            if (res>5) {
                                //给提示
                                msg.what=1;
                                handler.sendMessage(msg);
                            }
                            else{
                                ChangeEarly(bkpassword, username, context, view);
                            }
                        }else{
                            msg.what=5;
                            handler.sendMessage(msg);
                        }

                    }
                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }


        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);


    }
    public static void ChangeControl(final String bkpassword, final String username, final Context context, final View view){
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ControltimeServlet?bkpassword="+bkpassword+"&username="+username;
        RequestQueue mQueue = Volley.newRequestQueue(context);



        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Message msg=new Message();
                    Handler handler = new Handler()
                    {
                        public  void handleMessage(Message msg)
                        {
                            switch(msg.what)
                            {
                                case 1:
                                    Toast.makeText(context,"已接受控制，认真听课哦！",Toast.LENGTH_LONG).show();
                                    break;
                                case 2:
                                    Toast.makeText(context,"已接受控制，但是服务器出现了一些问题！",Toast.LENGTH_LONG).show();
                                    break;
                            }

                        }
                    };

                    boolean control=response.getBoolean("flag");
                    if(control){
                        msg.what=1;
                        handler.sendMessage(msg);
                    }else{
                        msg.what=2;
                        handler.sendMessage(msg);
                    }
                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }


        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);


    }
    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }
    private static double GetDistance(double longitude, double latitude, double longitude2, double latitude2) {
         double EARTH_RADIUS = 6371393;
        double long1 = rad(longitude);
        double long2 = rad(longitude2);
        double a = long1 - long2;
        double b = rad(latitude) - rad(latitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                Math.cos(long1)*Math.cos(long2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        return s;
    }



}
